package com.ymtms.settlement.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ymtms.settlement.dao.CustomerGoodsbillBalanceMapper;
import com.ymtms.settlement.dao.GoodsbillMasterMapper;
import com.ymtms.settlement.pojo.CustomerGoodsbillBalance;
import com.ymtms.settlement.pojo.GoodsbillMaster;
import com.ymtms.settlement.service.CustomerGoodsbillBalanceService;
import com.ymtms.settlement.vo.GridRequest;
import com.ymtms.settlement.vo.GridResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class CustomerGoodsbillBalanceServiceImpl implements CustomerGoodsbillBalanceService {
    @Autowired
    CustomerGoodsbillBalanceMapper customerGoodsbillBalanceMapper;
    @Autowired
    GoodsbillMasterMapper goodsbillMasterMapper;


    @Override
    public GridResult<GoodsbillMaster> queryGbmByPage(
            GridRequest gridRequest, GoodsbillMaster goodsbillMaster,
            String startTime, String endTime) {
        // 获取当前页和页大小
        Integer currentPage = gridRequest.getPage();
        Integer pageSize = gridRequest.getLimit();

        // 判断是否有排序,有则生成符合pagehelper的排序字符串
        String sidx = gridRequest.getSidx(); // 排序参数
        String sord = gridRequest.getSord(); // 排序规则

        // System.out.println(currentPage);
        // System.out.println(pageSize);
        // System.out.println(sidx);
        // System.out.println(sord);

        String orderBy = "";
        // pagehelper静态设置页属性方法，它会拦截下面的第一个查询！第二个无效。
        if(checkOrderBy(sidx, sord)){
            sidx = upperCharToUnderLine(sidx);
            orderBy = sidx+" "+sord;

            System.out.println(orderBy);

            PageHelper.startPage(currentPage, pageSize, orderBy);
        }else{
            // 设置当前页和页大小
            PageHelper.startPage(currentPage, pageSize);
        }

        // 查询结果（传入排序）
        List<GoodsbillMaster> result = goodsbillMasterMapper.selectByIfSettle(goodsbillMaster, startTime, endTime);

        // 利用当前页和页大小配置pageinfo
        PageInfo<GoodsbillMaster> pageList = new PageInfo<>(result);
        // 新建一个封装类对象，设置参数，传入查询得到的数据
        GridResult<GoodsbillMaster> grid = new GridResult<>();

        // 存入查询数据
        grid.setData(result);
        // 存入总条数
        grid.setCount(pageList.getTotal());

        return grid;
    }


    @Override
    public int save(Integer gmid, CustomerGoodsbillBalance customerGoodsbillBalance) {

        // 根据id查询对应数据
        GoodsbillMaster goodsbillMaster = goodsbillMasterMapper.selectOneByGmid(gmid);
        // 如果未查到（有可能已被修改），则抛出异常
        if(goodsbillMaster == null){
            throw new RuntimeException("结算失败，未找到对应数据！");
        }

        // 核对数据
        // 计算本单金额 = 运费+保险费+搬运费-减款
        BigDecimal carriage = goodsbillMaster.getCarriage(); // 运费
        BigDecimal carryGoodsFee = goodsbillMaster.getCarryGoodsFee(); // 搬货费
        BigDecimal insurance = goodsbillMaster.getInsurance(); // 保险费
        BigDecimal reduceFund = goodsbillMaster.getReduceFund(); // 减款
        BigDecimal moneyOfChangePay = goodsbillMaster.getMoneyOfChangePay(); // 预付金额
        BigDecimal billMoney = carriage.add(carryGoodsFee).add(insurance).subtract(reduceFund).setScale(2,BigDecimal.ROUND_HALF_UP);

        // 计算应收金额 = 本单金额-预付金额
        BigDecimal moneyReceivable = billMoney.subtract(moneyOfChangePay).setScale(2,BigDecimal.ROUND_HALF_UP);

        // 获取前台传来的已收金额
        BigDecimal receivedMoney = customerGoodsbillBalance.getReceivedMoney();

        // 判断金额是否一致
        if(moneyReceivable.doubleValue() != receivedMoney.doubleValue()){
            // System.out.println("货款");
            throw new RuntimeException("结算失败，应收金额与已收金额不一致");
        }

        GoodsbillMaster goodsbillMaster1 = new GoodsbillMaster();
        goodsbillMaster1.setGmid(gmid);
        // 代收货款
        BigDecimal helpAcceptPayment = goodsbillMaster.getHelpAcceptPayment();
        // 修改货运单的结账状态
        if (helpAcceptPayment.doubleValue() != new BigDecimal("0").doubleValue()) {
            goodsbillMaster1.setIfSettleAccounts("已运单结算");
        } else {
            goodsbillMaster1.setIfSettleAccounts("已代收结算");
        }
        int gmrow = goodsbillMasterMapper.updateByPrimaryKeySelective(goodsbillMaster1); // 修改货运单

        // 添加货运单结算表
        customerGoodsbillBalance.setCustomer(goodsbillMaster.getSendGoodsCustomer());
        customerGoodsbillBalance.setGoodsBillCode(goodsbillMaster.getGoodsBillCode());
        customerGoodsbillBalance.setBillMoney(billMoney);
        customerGoodsbillBalance.setMoneyReceivable(moneyReceivable);
        customerGoodsbillBalance.setReceivedMoney(receivedMoney);
        customerGoodsbillBalance.setPrepayMoney(moneyOfChangePay);
        customerGoodsbillBalance.setCarriageReduceFund(reduceFund);
        customerGoodsbillBalance.setBalanceTime(new Date());
        customerGoodsbillBalance.setInsurance(insurance);
        customerGoodsbillBalance.setCarryGoodsFee(carryGoodsFee);
        customerGoodsbillBalance.setFlag(0);
        int row = customerGoodsbillBalanceMapper.insert(customerGoodsbillBalance); // 插入数据
        if(row ==0 || gmrow == 0){
            throw new RuntimeException("结算失败！");
        }
        return 0;


    }

    /*-----------------------------货运单结算历史业务------------------------------*/

    /**
     * @description: 多条件分页查询代收结算历史
     * @param gridRequest 封装包含分页信息的类（当前页、页大小、排序字段、排序规则）
     * @param customerGoodsbillBalance 包含查询条件的实体类
     * @param startTime 时间范围查询条件（开始时间）
     * @param endTime 时间范围查询条件（结束时间）
     * @return: 返回类包含实体类集合和前端layui分页条件
     * @author: 张泓
     * @date: 2019/10/25
     */
    @Override
    public GridResult<CustomerGoodsbillBalance> queryCmbByPage(
            GridRequest gridRequest, CustomerGoodsbillBalance customerGoodsbillBalance,
            String startTime, String endTime) {

        // 获取当前页和页大小
        Integer currentPage = gridRequest.getPage();
        Integer pageSize = gridRequest.getLimit();

        // 判断是否有排序,有则生成符合pagehelper的排序字符串
        String sidx = gridRequest.getSidx(); // 排序参数
        String sord = gridRequest.getSord(); // 排序规则

        /*System.out.println(currentPage);
        System.out.println(pageSize);
        System.out.println(sidx);
        System.out.println(sord);*/

        String orderBy = "";
        // pagehelper静态设置页属性方法，它会拦截下面的第一个查询！第二个无效。
        if(checkOrderBy(sidx, sord)){
            sidx = upperCharToUnderLine(sidx);
            orderBy = sidx+" "+sord;

            System.out.println(orderBy);

            PageHelper.startPage(currentPage, pageSize, orderBy);
        }else{
            // 设置当前页和页大小
            PageHelper.startPage(currentPage, pageSize);
        }

        // 查询结果（传入排序）
        List<CustomerGoodsbillBalance> result = customerGoodsbillBalanceMapper.selectByCondition(customerGoodsbillBalance, startTime, endTime);

        // 利用当前页和页大小配置pageinfo
        PageInfo<CustomerGoodsbillBalance> pageList = new PageInfo<>(result);
        // 新建一个封装类对象，设置参数，传入查询得到的数据
        GridResult<CustomerGoodsbillBalance> grid = new GridResult<>();

        // 存入查询数据
        grid.setData(result);
        // 存入总条数
        grid.setCount(pageList.getTotal());

        return grid;
    }

    /**
     * @description: 软删除
     * @param cgsid 表主键
     * @return: int
     * @author: 邱斌雨
     * @date: 2019/10/25
     */
    @Override
    public int removeByCgsid(Integer cgsid) {
        return customerGoodsbillBalanceMapper.deleteByCgsid(cgsid);
    }

    /**
     * @description: 批量软删除
     * @param keys 表主键数组
     * @return: int
     * @author: 邱斌雨
     * @date: 2019/10/25
     */
    @Override
    public int batchRemoveByCgsid(Integer[] keys) {
        return customerGoodsbillBalanceMapper.batchDeleteByCgsid(keys);
    }

    /*--------------------------------工具类------------------------------*/

    /**
     * @description: 判断排序字段和排序规则字符串是否非空
     * @param sidx 排序字段
     * @param sord 排序规则
     * @return: true则非空
     * @author: 张泓
     * @date: 2019/10/25
     */
    private boolean checkOrderBy(String sidx,String sord){
        if(sidx != null && sord != null
                && sidx.trim().length() > 0
                && sord.trim().length() > 0){
            return true;
        }
        return false;
    }

    /**
     * @description: 大写转换为下划线+小写
     * @param param 需要转换的字符串
     * @return: 返回转换后的字符串
     * @author: 张泓
     * @date: 2019/10/25
     */
    public static String upperCharToUnderLine(String param) {
        Pattern p = Pattern.compile("[A-Z]");
        if (param == null || param.equals("")) {
            return "";
        }
        StringBuilder builder = new StringBuilder(param);
        Matcher mc = p.matcher(param);
        int i = 0;
        while (mc.find()) {
            System.out.println(builder.toString());
            System.out.println("mc.start():" + mc.start() + ", i: " + i);
            System.out.println("mc.end():" + mc.start() + ", i: " + i);
            builder.replace(mc.start() + i, mc.end() + i, "_" + mc.group().toLowerCase());
            i++;
        }

        if ('_' == builder.charAt(0)) {
            builder.deleteCharAt(0);
        }
        return builder.toString();
    }
}
